import numpy as np
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from numpy.linalg import eig
#matplotlib inline
# 解决中文输出问题
font = {"size": 15, "family": "fangsong"}
matplotlib.rc("font", **font)
matplotlib.rcParams['axes.unicode_minus']=False
iris = load_iris()
X = iris.data
X = X - X.mean(axis=0)
print(X)
#计算协方差矩阵
X_cov = np.cov(X.T, ddof=0)  # ddof :如果不是"无”，则将覆盖由偏置隐含的默认值。请注意，即使同时指定了权重和权重，ddof = 1也会返回无偏估计。

#计算协方差矩阵的特征值和特征向量
eigenvalues, eigenvectors = eig(X_cov)

tot = sum(eigenvalues)
var_exp = [(i/tot) for i in sorted(eigenvalues, reverse = True)]
cum_var_exp = np.cumsum(var_exp)

plt.bar(range(1, 5), var_exp, alpha=0.5, align='center', label='风险值')
plt.step(range(1, 5), cum_var_exp, where='mid', label='累积值')
plt.ylabel('方差脉冲')
plt.xlabel('主成分')
plt.legend(loc='best')
plt.show()
